import axios from "axios";
import {
	clearEmptyParam
} from './clearEmptyParam'
import api from "./api";

const request = axios.create({
	baseURL: 'http://8.138.162.67:8085/officialWebsite/',
	timeout: '5000s',
})

request.interceptors.request.use(config => {

	config.headers['Content-Type'] = "application/x-www-form-urlencoded"

	if (localStorage.getItem('token')) {
		config.headers['X-Access-Token'] = `${localStorage.getItem('token')}`
	}

	clearEmptyParam(config)

	return config;
})

request.interceptors.response.use(res => {
		if (res.headers['token']) {
			localStorage.setItem('token', res.headers['token'])
		}

		return res.data;
	},
	err => {
		// if (err.response.status == 401) {
		// 	localStorage.removeItem('token')
		// }
		return Promise.reject(new Error(err))
	})

export function handleRequest(key, data, params) {
	if (!api[key]) {
		return console.error('无效key');
	}

	if (api[key].auth) {
		if (!localStorage.getItem('token')) {
			console.error('需要登录')
			return {
				then() {}
			};
		}
	}

	return request({
		...api[key],
		data,
		params
	})
};

export default handleRequest